package com.czm.art_light.context;

import com.czm.art_light.patterns.strategy.UserActionStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户行为类型的策略设计模式管理类
 */
@Component
public class UserActionStrategyContext implements ApplicationContextAware {
    // 在该Map中存储所有的策略对象
    private static final Map<String, UserActionStrategy> userActionStrategyHashMap = new HashMap<>();

    // 定义从Map中获取具体策略对象的方法
    public  UserActionStrategy getSaveOrderStrategy(String payWay) {
        return userActionStrategyHashMap.get(payWay);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 获取所有的策略 bean
        Map<String, UserActionStrategy> beans = applicationContext.getBeansOfType(UserActionStrategy.class);
        // 循环添加到Map中
        beans.values().forEach(userActionStrategy->
                userActionStrategyHashMap.put(userActionStrategy.getAction(), userActionStrategy)
        );
    }
}
